package com.sanq.product.books.service.impl;

import com.sanq.product.books.es.service.AreaService;
import com.sanq.product.books.mapper.AreaMapper;
import com.sanq.product.config.utils.ip.IPLocation;
import com.sanq.product.config.utils.ip.IPSeeker;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * com.sanq.product.books.service.impl.AreaServiceImpl
 *
 * @author sanq.Yan
 * @date 2019/8/31
 */
@Service("areaService")
public class AreaServiceImpl implements AreaService {

    @Value("${ip.path}")
    public String ipPath;
    @Resource
    private JedisPoolService jedisPoolService;
    @Resource
    private AreaMapper areaMapper;

    @Override
    public Map<String, String> getCityNameByIp(String ip) {
        Map<String, String> map = null;

        String json = jedisPoolService.get(String.format("ip:%s", ip));

        if (StringUtil.isEmpty(json)) {
            IPLocation ipLocation = null;
            try {
                ipLocation =
                        IPSeeker.getInstance(ipPath)
                                .getIPLocation(ip);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                map = areaMapper.getCityNameByIp(ipLocation.getCountry());
                if (map != null && !map.isEmpty())
                    jedisPoolService.set(String.format("ip:%s", ip), JsonUtil.obj2Json(map));
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else map = JsonUtil.json2Obj(json, Map.class);

        return map;
    }
}
